<!--地区销售排行-->
<template>
  <div class="com-container">
    <div class="com-chart" id="rank"></div>
  </div>
</template>

<script setup>
import { onMounted,onBeforeUnmount, inject, reactive, ref, watch } from "vue";
import { getRankData } from "@/service/getChartsData";
import {useStore} from "vuex";

// 1. 接收Echarts
let echarts = inject('echarts')
let chartInstance = reactive({})
// 2. 定义接收数据变量
let chartDate = reactive([])
let xData = reactive([])
let yData = reactive([])
let titleFontSize = ref(null)
let timer = reactive({})
let startBar = ref(0)
let endBar = ref(9)
const store =useStore()

function initChart() {
  chartInstance = echarts.init(document.querySelector("#rank"), store.state.theme)

  const initOption = {
    title:{
      text: '▎ 地区销售排行',
      left: '20',
      top: '20'
    },
    grid:{
      top: '40%',
      left: '5%',
      right: '5%',
      bottom: '5%',
      containLabel: true // 定位是否包含坐标轴数据
    },
    tooltip:{
      show: true
    },
    xAxis:{
      type:'category'
    },
    yAxis:{
      type:'value'
    },
    series:[
      {
        type: 'bar'
      }
    ]
  }

  chartInstance.setOption(initOption)

}

async function getChartData() {
  let {data: res} = await getRankData()
  chartDate = res
}

function setChartData(){
  chartDate.sort((a, b) => b.value - a.value)
  xData = chartDate.map( item => item.name)
  yData = chartDate.map( item => item.value)

}

function updateChart() {
  setChartData()

  const colorArr = [
    ['#0BA82C', '#4FF778'],
    ['#2E72BF', '#23E5E5'],
    ['#5052EE', '#AB6EE5']
  ]

  const updateOption = {
    xAxis: {
      data: xData
    },
    // 滑动条配置
    dataZoom:{
      show: false, //是否显示滑动条
      startValue: startBar.value, // 从1条柱开始显示
      endValue: endBar.value   // 从10条柱结束显示，一共显示10条
    },
    series:[
      {
        data: yData,
        itemStyle:{
          color: (target) => {
             let targetColorArr = null
             if (target.value > 300) {
               targetColorArr = colorArr[0]
             }else if (target.value > 200) {
               targetColorArr = colorArr[1]
             }else {
               targetColorArr = colorArr[2]
             }
             return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
               {
                 offset: 0,
                 color:targetColorArr[0]
               },
               {
                 offset: 1,
                 color:targetColorArr[1]
               }
             ])

          }
        }
      }
    ]

  }
  chartInstance.setOption(updateOption)
}

// 为图表添加移入、移出事件
function addEvent(){
  chartInstance.on('mouseover',() => {
    clearInterval(timer)
  })
  chartInstance.on('mouseout',() => {
    startInterval()
  })
}

function startInterval() {
  if(timer){
    clearInterval(timer)
  }

  timer = setInterval(() => {
    startBar.value++
    endBar.value++
    if (endBar.value> chartDate.length-1){
      startBar.value = 0
      endBar.value = 9
    }

    updateChart()
  }, 1000)
}

function screenAdapter() {
  titleFontSize.value = document.querySelector("#rank").offsetWidth / 100 * 3.6
  const adapterOption = {
    title:{
      textStyle:{
        fontSize:titleFontSize.value
      }
    },
    series: [
      {
        barWidth:titleFontSize.value,
        itemStyle: {
          barBorderRadius:[titleFontSize.value / 2, titleFontSize.value / 2, 0, 0], //设置柱的圆角（顺序： 左上，右上，右下，左下）
        }
      }
    ]
  }
  chartInstance.setOption(adapterOption)
  chartInstance.resize()
}

watch(() => store.state.theme, () => {
  //console.log('主题切换了')
  chartInstance.dispose()//销毁当前的图表
  initChart()//重新初始化图表对象
  updateChart()//更新图表的展示
  screenAdapter()//完成屏幕的适配
})

onMounted(() => {
   initChart()
   getChartData().then(() => {
     updateChart()
     startInterval()
     addEvent()
     screenAdapter()
   })
  window.addEventListener('resize',screenAdapter)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize',screenAdapter)
  clearInterval(timer)
})

// 导出 适配函数 以便父组件screenPage使用
defineExpose ({
  screenAdapter
})

</script>

<style scoped>

</style>